<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">{{ $t("login.form.title") }}</div>
    <div class="login-form-sub-title">{{ $t("login.form.title") }}</div>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-form ref="formRef" :model="userInfo" class="login-form" layout="vertical" @finish="handleSubmit">
      <a-form-item name="username" :rules="[{ required: true, message: $t('login.form.userName.errMsg'), trigger: 'blur' }]">
        <a-input v-model:value="userInfo.username" :placeholder="$t('login.form.userName.placeholder')">
          <template #prefix>
            <UserOutlined style="color: rgb(78, 89, 105); margin-right: 12px" />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item name="password" :rules="[{ required: true, message: $t('login.form.password.errMsg'), trigger: 'blur' }]">
        <a-input-password v-model:value="userInfo.password" :placeholder="$t('login.form.password.placeholder')" allow-clear>
          <template #prefix>
            <LockOutlined style="color: rgb(78, 89, 105); margin-right: 12px" />
          </template>
        </a-input-password>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox checked="rememberPassword" :model-value="loginConfig.rememberPassword" @change="setRememberPassword as any">
            {{ $t("login.form.rememberPassword") }}
          </a-checkbox>
          <a-button type="link" @click="handleForgetPassword">{{ $t("login.form.forgetPassword") }}</a-button>
        </div>
        <a-button type="primary" html-type="submit" block :loading="loading">
          {{ $t("login.form.login") }}
        </a-button>
        <a-button type="text" block class="login-form-register-btn" @click="handleRegister">
          {{ $t("login.form.register") }}
        </a-button>
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue"
import { useStorage } from "@vueuse/core"
import { useI18n } from "vue-i18n"
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue"
import { message } from "ant-design-vue"
import { useUserStore } from "@/store"
import router from "@/router"
import useLoading from "@/hooks/loading"
import { cryptoDecode, cryptoEncode } from "@/utils/crypto"
import { LoginData } from "@/api/user"
import { HOME_ROUTE_NAME } from "@/router/constants"

const emits = defineEmits(["register", "forget"])
const { t } = useI18n()
const errorMessage = ref("")
const { loading, setLoading } = useLoading()
const userStore = useUserStore()

const loginConfig = useStorage("login-config", {
  rememberPassword: true,
  username: "",
  password: ""
})
const userInfo = reactive({
  username: loginConfig.value.username,
  password: cryptoDecode(loginConfig.value.password || "")
})
const setRememberPassword = (value: boolean) => {
  loginConfig.value.rememberPassword = value
}
const handleRegister = () => {
  emits("register")
}

const handleForgetPassword = () => {
  emits("forget")
}

let formRef = ref()
const handleSubmit = async (values: any) => {
  setLoading(true)
  try {
    await userStore.login(values as LoginData)
    const { redirect, ...othersQuery } = router.currentRoute.value.query
    router.push({
      name: (redirect as string) || HOME_ROUTE_NAME,
      query: {
        ...othersQuery
      }
    })
    message.success(t("login.form.login.success"))
    const { rememberPassword } = loginConfig.value
    const { username, password } = values
    // 实际生产环境需要进行加密存储。
    // The actual production environment requires encrypted storage.
    loginConfig.value.username = rememberPassword ? username : ""
    loginConfig.value.password = rememberPassword ? cryptoEncode(password) : ""
  } catch (err) {
    errorMessage.value = (err as Error).message
  } finally {
    setLoading(false)
  }
}
</script>

<style lang="scss" scoped>
.login-form {
  &-wrapper {
    width: 320px;
  }

  &-title {
    font-size: 24px;
    color: #1d2129;
    font-weight: 500;
    line-height: 32px;
  }

  &-sub-title {
    font-size: 16px;
    color: #86909c;
    line-height: 24px;
  }

  &-error-msg {
    height: 32px;
    color: #f53f3f;
    line-height: 32px;
  }

  &-password-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  &-register-btn {
    color: #86909c !important;
  }
  :deep(.ant-input-affix-wrapper) {
    background-color: #f2f3f5;
    border: none;
    color: #1d2129;
    border-radius: 0;
    height: 32px;
    input {
      background-color: #f2f3f5;
    }
  }
}
</style>
